package cn.apiManager.web.action;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.apiManager.common.Constant;
import cn.apiManager.entity.UserInfo;
import cn.apiManager.service.UserInfoService;
import cn.apiManager.utils.ResultVo;



@Controller
public class IndexAction extends BaseAction {
	private static final Logger logger = LoggerFactory.getLogger(IndexAction.class);

	@Resource
	private UserInfoService userInfoService;
	
	/**
	 * 主页面
	 */
	@RequestMapping("/")
	public String redirectLogin(){
		return "index";
	}
	
	/**
	 * 登陆
	 * @return
	 */
	@RequestMapping("/login")
	public String login() {
		return "login";
	}
	
	/**
	 * 注册
	 * @return
	 */
	@RequestMapping("/register")
	public String register() {
		return "register";
	}
	
	/**
	 * 项目管理
	 */
	@RequestMapping("/project")
	public String project(){
		return "/project-index";
	}
	
	/**
	 * 处理注册信息
	 * @param email
	 * @param password
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/doLogin")
	@ResponseBody
	public ResultVo doLogin(@RequestParam String email,@RequestParam String password,HttpServletRequest request, HttpServletResponse response) {
		ResultVo vo = new ResultVo();
		vo.setResult(false);

		UserInfo example = new UserInfo();
		example.setEmail(email);
		example.setPassWord(password);

		List<UserInfo> list = userInfoService.selectByExampleList(example);
		if (!CollectionUtils.isEmpty(list)) {
        	request.getSession().setAttribute(Constant.COOKIE_LOGIN_NAME_KEY, list.get(0));
			vo.setMessage("登陆成功！");
			vo.setResult(true);
		}else{
			vo.setStatus(500);
			vo.setMessage("登陆失败！账号或密码错误！");
		}

		return vo;
	}
	
	/**
	 * 退出
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/logout")
	public String logout(HttpServletRequest request,HttpServletResponse response){
		request.getSession().removeAttribute(Constant.COOKIE_LOGIN_NAME_KEY);
		return "redirect:/";
	}

	

}
